﻿using MicroMq.Helper;
using MicroMq.Options;

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

using Peer;

using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace MicroMq.Hosts
{
    class PeerHost : IHostedService
    {
        private readonly MicroMqOptions options;
        private readonly PeerServer peerServer;
        private readonly MqConnectionManager connectionManager;

        private readonly ILogger<PeerHost> logger;
        public PeerHost(IOptions<MicroMqOptions> optionsMonitor, MqConnectionManager connectionManager, ILogger<PeerHost> logger)
        {
            this.options = optionsMonitor.Value;
            this.logger = logger;
            this.connectionManager = connectionManager;
            peerServer = new PeerServer(options.Cipher, new IPEndPoint(IPAddress.Any, options.Port));
            peerServer.OnAccept += PeerServer_OnAccept;
        }



        private void PeerServer_OnAccept(object sender, PeerStream e)
        {
            connectionManager.Accept(e);
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            var logText = peerServer.Listen(10, cancellationToken);
            logger.LogInformation($"started: { logText}");
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            try
            {
                peerServer.Dispose();
            }
            catch (System.Exception)
            {

            }
            return Task.CompletedTask;
        }
    }
}
